//
//  CollectRequest.m
//  SleepingElf
//
//  Created by karong on 2023/10/25.
//

#import "CollectRequest.h"
#import "CollectModel.h"

@implementation CollectRequest

+ (void)loadCollectListWithPage:(NSInteger)page success:(ArrayBlock)success failed:(Failure)failed {
    NSString * url = API_MUSIC_COLLECT_LIST;
    NSMutableDictionary * parameters = [NSMutableDictionary new];
    parameters[@"page"] = @(page);
    parameters[@"pagesize"] = @(10);
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        NSArray * array = [CollectModel mj_objectArrayWithKeyValuesArray:responseDict[@"data"]];
        NSMutableArray * musicArray = [NSMutableArray new];
        for (CollectModel * collectModel in array) {
            [musicArray addObjectsFromArray:collectModel.music_data];
        }
        success(musicArray);
    } failure:failed];
}
#pragma mark - PagableRequestPotocol
- (void)refreshDataSuccess:(ArrayBlock)success failed:(Failure)failed {
    if (self.loading) {
        return;
    }
    self.loading = YES;
    self.haveMore = YES;
    self.page = 1;
    [CollectRequest loadCollectListWithPage:self.page success:^(NSArray *array) {
        [self loadSuccess:success withArray:array];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        failed(response, error, responseObject);
        self.loading = NO;
    }];
}


- (void)loadMoreDataSuccess:(ArrayBlock)success failed:(Failure)failed {
    if (self.loading && !self.haveMore) {
        return;
    }
    
    [CollectRequest loadCollectListWithPage:self.page success:^(NSArray *array) {
        [self loadSuccess:success withArray:array];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        failed(response, error, responseObject);
        self.loading = NO;
    }];
}

- (void)loadSuccess:(ArrayBlock)success withArray:(NSArray *)array {
    self.haveMore = !(array.count < self.pageSize);
    self.page++;
    self.loading = NO;
    success(array);
}
@end
